import { LoginDto } from "../dto/login.dto";
import { WeChatService } from "nest-wechat";
import { HttpException, Inject } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { UserEntity } from "../entity/user.entity";
import { Repository } from "typeorm";
import { JwtService } from "@nestjs/jwt";
import { code2Session, getAccessToken, getPhoneNumber } from "../utils/wechat";

export class LoginService {


  @InjectRepository(UserEntity)
  private readonly usersRepository: Repository<UserEntity>;

  @Inject()
  private readonly weChatService: WeChatService;

  @Inject()
  private readonly jwtService: JwtService;

  async login(loginDto: LoginDto) {

    const session = await code2Session(
      loginDto.code,
      this.weChatService.config.appId,
      this.weChatService.config.secret
    );

    if (session.errcode !== undefined) {
      throw new HttpException(`微信授权失败[${session.errmsg}]`, 500);
    }
    //判断用户是否存在
    let user = await this.usersRepository.findOne({
      where: {
        openid: session.openid
      }
    });

    if (user === null) {
      const newUser = new UserEntity();
      newUser.openid = session.openid;
      newUser.nickname = loginDto.nickname;
      newUser.avatar = loginDto.avatar;
      newUser.mobile = loginDto.phone;
      user = await this.usersRepository.save(newUser);
    }else {
      //更新用户头像和昵称
      user.nickname = loginDto.nickname;
      user.avatar = loginDto.avatar;
      user = await this.usersRepository.save(user);
    }

    return {
      accessToken: this.jwtService.sign({
        uid: user.id,
        openid: user.openid
      })
    };
  }

  async getPhoneNumber(phoneCode: string) {
    const accessToken = await getAccessToken(
      this.weChatService.config.appId,
      this.weChatService.config.secret
    );

    if (accessToken.data.errcode) {
      throw new HttpException(`获取手机号失败[${accessToken.data.errmsg}]`, 500);
    }

    const phoneResp = await getPhoneNumber(phoneCode, accessToken.data.access_token);

    if (phoneResp.data.errcode !== 0) {
      throw new HttpException(`获取手机号失败[${phoneResp.data.errmsg}]`, 500);
    }

    return phoneResp.data.phone_info.purePhoneNumber;
  }
}
